package com.huiqiao.lesson10.service;


import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

import com.huiqiao.lesson10.mapper.AccountMapper;
import com.huiqiao.lesson10.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 账户余额Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-07
 */
@Service
public class AccountService {
    @Autowired
    private AccountMapper accountMapper;

    /**
     * 查询账户余额
     *
     * @param id 账户余额主键
     * @return 账户余额
     */

    public Account selectAccountById(Long id) {
        return accountMapper.selectAccountById(id);
    }

    /**
     * 查询账户余额列表
     *
     * @param account 账户余额
     * @return 账户余额
     */

    public List<Account> selectAccountList(Account account) {
        return accountMapper.selectAccountList(account);
    }

    /**
     * 新增账户余额
     *
     * @param account 账户余额
     * @return 结果
     */

    public int insertAccount(Account account) {
        return accountMapper.insertAccount(account);
    }

    /**
     * 修改账户余额
     *
     * @param account 账户余额
     * @return 结果
     */

    public int updateAccount(Account account) {
        return accountMapper.updateAccount(account);
    }

    /**
     * 批量删除账户余额
     *
     * @param ids 需要删除的账户余额主键
     * @return 结果
     */

    public int deleteAccountByIds(Long[] ids) {
        return accountMapper.deleteAccountByIds(ids);
    }

    /**
     * 删除账户余额信息
     *
     * @param id 账户余额主键
     * @return 结果
     */

    public int deleteAccountById(Long id) {
        return accountMapper.deleteAccountById(id);
    }


    /**
     * 转账场景 - 声明式事务
     */
    @Transactional(rollbackFor = Exception.class)
    public void transferAccount() {
        Account alice = selectAccountById(1L);
        Account bob = selectAccountById(2L);

        BigDecimal num = new BigDecimal(100);
        alice.setBalance(alice.getBalance().add(num));
        accountMapper.updateAccount(alice);

        bob.setBalance(bob.getBalance().subtract(num));
        accountMapper.updateAccount(bob);
    }
}
